import xlrd
from Automation_frame.parsing.Test_cases import Mycase
class Parser(object):
    path = r'../test_data/Test_data.xlsx'
    def __init__(self,filename=path):
        self.filepath=filename
        self.book=None
        self.sheet=None
    def get_book(self):
        '''
        打开Excel文件读取数据，方便下面的get_sheet继承使用
        :return:
        '''
        try:
            self.book=xlrd.open_workbook(self.filepath)
        except Exception as e:
            print(r'get_book:文件出现了问题',e)
    def get_sheet(self,sheetname='Sheet1'):
        '''
        获取sheet名称页面的所有数据
        :param sheetname:页面名
        :return:页面所有数据
        '''
        try:
            self.get_book()    #打开Excel文件读取数据
            self.sheet=self.book.sheet_by_name(sheetname)   #通过名称获取数据
            return self.sheet
        except Exception as e:
            print(e)
    def Parser_xl(self):
        list=[]
        try:
            # self.get_sheet()
            nrows=self.sheet.nrows
            for i in range(1,nrows):
                data=self.sheet.row_values(i)
                case=Mycase()
                case.caseid=data[0]
                case.descrition=data[1]
                case.module=data[2]
                # case.function=data[3]
                case.testdata=self.get_casedata(data[3])
                case.mark=data[4]
                list.append(case)
            return list
        except Exception as e:
            print('Parser:',e)
    def get_casedata(self,testdata):
        list=[]
        for i in testdata.splitlines():
            data=i.split(' ')
            case={}
            if len(data)==2:
                case['key']=data[0]
                case['object']=data[1]

            elif len(data)==3:
                case['key']=data[0]
                case['object']=data[1]
                case['param']=data[2]
            else:
                print(f'测试用例数据不正确：{testdata}')
            list.append(case)
        return list
if __name__ == '__main__':
    a=Parser(r'../test_data/testdata998.xls')
    a.get_sheet(sheetname='KDT')
    # a.get_sheet()
    # print(a)
    a=a.Parser_xl()
    for i in a:
        print(i.testdata)
